#include "ipc_client.h"

#include <arpa/inet.h>
#include <mutex>
#include <string.h>
#include <unistd.h>

sptr<IpcClient> IpcClient::GetInstance()
{
    if (instance == nullptr) {
        static std::mutex mutex;
        std::lock_guard<std::mutex> lock(mutex);
        if (instance == nullptr) {
            instance = new IpcClient();
        }
    }
    return instance;
}

int IpcClient::Connect(std::string address, uint16_t port)
{
    socketFd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(port),
        .sin_addr = {
            .s_addr = inet_addr(address.c_str())
        },
    };
    return connect(socketFd, (struct sockaddr *)&addr, sizeof(struct sockaddr));
}

int IpcClient::Send(IpcMessageParcel &parcel)
{
    return parcel.Write(socketFd);
}

int IpcClient::Recv(IpcMessageParcel &reply)
{
    return reply.Read(socketFd);
}

void IpcClient::Disconnect()
{
    close(socketFd);
}
